var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var cors = require("cors");

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var cypRouter = require("./routes/cyp");
var mzhRouter = require("./routes/mzh");
var zqRouter = require("./routes/zq");
var rxhRouter = require("./routes/rxh");
var zslRouter = require("./routes/zsl");
var cjzRouter = require("./routes/cjz");
var gjsRouter = require("./routes/gjs");
var app = express();
var router = express.Router();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use("/upload", express.static("upload"));
//每个人的路由地址
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/cyp", cypRouter);
app.use("/mzh", mzhRouter);
app.use("/zq", zqRouter);
app.use("/rxh", rxhRouter);
app.use("/zsl", zslRouter);
app.use("/cjz", cjzRouter);
app.use("/gjs", gjsRouter);

const { crowdModel } = require("./model/zq");
// websocket服务器连接
const msList = [];
const msIdList = [];
const { WebSocketServer } = require("ws");
const server = new WebSocketServer({port:8088})

server.on("connection", handleConnection);

function handleConnection(ws, req) {
  console.log("------server-------已连接");

  ws.on("close", handleClose);
  ws.on("error", handleError);
  ws.on("message", handleMessage);

  const id = req.url.split("=")[1];
  ws["id"] = id;

  if (msIdList.indexOf(id) == -1) {
    msIdList.push(id);
    msList.push(ws);
    console.log(msIdList, "··············用户登录ID···············");
  }

  function handleMessage(data) {
    console.log("客户端数据:::", JSON.parse(data.toString()));
    const { mode, cronys, sender, toid, id, message ,latitude,longitude,xls,time,voicetime,name,types,basevideo} = JSON.parse(
      data.toString()
    );
    // console.log(mode, cronys, sender, toid, id, message ,latitude,longitude,xls,time,voicetime,name,types, 6666666666666);
    switch (mode) {
      case "MESSAGE":
        msList.forEach((item) => {
          const response = {
            mode: "MESSAGE",
            message: message,
            sender: id,
            toid: toid,
            latitude,
            longitude,
            xls,
            time,
            voicetime,
            name,
            types,
            basevideo
          };
          if (item.id === toid) {
            item.send(JSON.stringify(response));
          }
        });
        break;
      case "HEART_BEAT父方法":
        //打印经纬度数据
        let idx;
        let data;
        async function crowdDate() {
          data = await crowdModel.find();
          idx = Math.floor(Math.random() * data.length);
          // console.log(data[idx]);
          const response = {
            mode: "HEART_BEAT父方法",
            messaged: "I am still connected",
            longitude: data[idx].longitude,
            latitude: data[idx].latitude,

          };
          ws.send(JSON.stringify(response));
        }
        crowdDate();
        break;
      default:
        break;
    }
  }

  function handleClose() {
    console.log("--- Server is closed 服务器已关闭 ---");
    ws.send(
      JSON.stringify({
        mode: "MESSAGE",
        msg: "--- Server is closed 服务器已关闭 ---",
      })
    );
  }

  function handleError(e) {
    console.log("--- Server occured error 服务器发生错误 ---", e);
  }
}

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
